package com.framework.core.mybatis.context;

import com.framework.core.mybatis.config.MybatisDdlProperties;
import com.framework.core.mybatis.ddl.IMybatisDdlFactory;
import com.framework.core.mybatis.util.ProcessUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.DisposableBean;

import java.util.ArrayList;
import java.util.List;

/**
 *  上下文
 *  created by zzg
 *  2024-12-06
 */
@Slf4j
@Data
public class TableContext {
    private SqlSessionFactory sqlSessionFactory;
    private List<TableInfo> tableInfoList = new ArrayList<>(16);
    private IMybatisDdlFactory ddlFactory;
    private MybatisDdlProperties properties;

    public TableContext(SqlSessionFactory sqlSessionFactory, IMybatisDdlFactory factory, MybatisDdlProperties properties) {
        this.sqlSessionFactory = sqlSessionFactory;
        this.ddlFactory = factory;
        this.properties = properties;
    }

    public void init() {
        if (!properties.getGenerateDdl()) {
            disposableBean();
            return;
        }
        List<Class<?>> classList = ProcessUtil.scanPackage(properties.getTypeAliasesPackage());
        ProcessUtil.convert2TableInfo(classList, tableInfoList);
        ddlFactory.execute(this);
    }

    private void disposableBean() {
        if (ddlFactory instanceof DisposableBean) {
            try {
                ((DisposableBean) ddlFactory).destroy();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        if (properties instanceof DisposableBean) {
            try {
                ((DisposableBean) properties).destroy();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }
}
